import {reactive, ref, computed, onMounted, h} from "vue";
import {listKctz, addKctz, updateKctz, deleteKctz} from "@/api/mpz/kctz";
import {type PaginationProps} from "@pureadmin/table";
import {message} from "@/utils/message";
import {type KctzFormItemProps} from "./types";
import {addDialog} from "@/components/ReDialog";
import editForm from "../form.vue";

export function useKctzForList() {

    const addFormRefKctz = ref();

    /**
     * 查询表单
     */
    const loadingKctz = ref(true);
    const searchFormKctz = reactive({
        id: undefined,
        reportDate: undefined,
        loadingTime: undefined,
        dumpTime: undefined,
        classNo: undefined,
        truckName: undefined,
        truckId: undefined,
        driverName: undefined,
        driverId: undefined,
        totalVc: undefined,
        totalOutput: undefined,
        pageNo: 1,
        pageSize: 10
    });


    /**
     * 列表
     */
    const paginationKctz = reactive<PaginationProps>({
        total: 0,
        pageSize: 10,
        currentPage: 1,
        background: true
    });

    const kctzColumns: TableColumnList = [
        {
            label: "主键",
            prop: "id",
            width: 70,
            fixed: "left"
        },
        {
            label: "日期",
            prop: "reportDate ",
            width: 70,
            fixed: "left"
        },
        {
            label: "装载时间",
            prop: "loadingTime",
            width: 70,
            fixed: "left"
        },
        {
            label: "卸矿时间",
            prop: "dumpTime",
            width: 70,
            fixed: "left"
        },
        {
            label: "班次（白班，夜班）",
            prop: "classNo",
            width: 70,
            fixed: "left"
        },
        {
            label: "卡车",
            prop: "truckName ",
            width: 70,
            fixed: "left"
        },
        {
            label: "卡车id",
            prop: "truckId",
            width: 70,
            fixed: "left"
        },
        {
            label: "司机",
            prop: "driverName ",
            width: 70,
            fixed: "left"
        },
        {
            label: "司机id",
            prop: "driverId",
            width: 70,
            fixed: "left"
        },
        {
            label: "总车数",
            prop: "totalVc",
            width: 70,
            fixed: "left"
        },
        {
            label: "总产量",
            prop: "totalOutput",
            width: 70,
            fixed: "left"
        },
    ];

    const kctzDataList = ref([]);

    async function onSearchKctz() {
        loadingKctz.value = true;
        for (const key in searchFormKctz) {
            if (Object.prototype.hasOwnProperty.call(searchFormKctz, key)) {
                const element = searchFormKctz[key];
                if ("" == searchFormKctz[key] && searchFormKctz[key].length == 0) {
                    searchFormKctz[key] = undefined;
                }
            }
        }
        const {data} = await listKctz(searchFormKctz);
        kctzDataList.value = data.records;
        paginationKctz.total = data.totalNum;

        setTimeout(() => {
            loadingKctz.value = false;
        }, 500);
    }

    const resetSearchFormKctz = formEl => {
        if (!formEl) return;
        formEl.resetFields();
        onSearchKctz();
    };

    onMounted(() => {
        onSearchKctz();
    });


    function handleSizeChangeKctz(val: number) {
        console.log(`${val} items per page`);
        searchFormKctz.pageSize = val;
        onSearchKctz();
    }

    function handleCurrentChangeKctz(val: number) {
        console.log(`current page: ${val}`);
        searchFormKctz.pageNo = val;
        onSearchKctz();
    }

    function handleSelectionChangeKctz(val) {
        console.log("handleSelectionChange", val);
        debugger;
    }

    function handleDeleteKctz(row) {
        deleteKctz(row.id).then(res => {
            if (res.code == 0) {
                message(`数据删除成功`, {
                    type: "success"
                });
                onSearchKctz(); // 刷新表格数据
            } else {
                message(`数据删除失败`, {
                    type: "error"
                });
            }
        });
    }


    function openDialogKctz(title = "新增", row?: KctzFormItemProps) {
        addDialog({
            title: `${title}指标对象`,
            props: {
                formInline: {
                    id: row?.id ?? undefined,
                    reportDate: row?.reportDate ?? undefined,
                    loadingTime: row?.loadingTime ?? undefined,
                    dumpTime: row?.dumpTime ?? undefined,
                    classNo: row?.classNo ?? undefined,
                    truckName: row?.truckName ?? undefined,
                    truckId: row?.truckId ?? undefined,
                    driverName: row?.driverName ?? undefined,
                    driverId: row?.driverId ?? undefined,
                    totalVc: row?.totalVc ?? undefined,
                    totalOutput: row?.totalOutput ?? undefined,
                }
            },
            width: "40%",
            draggable: true,
            fullscreenIcon: true,
            closeOnClickModal: false,
            contentRenderer: () => h(editForm, {ref: addFormRefKctz}),
            beforeSure: (done, {options}) => {
                const FormRef = addFormRefKctz.value.getRef();
                const curData = options.props.formInline as KctzFormItemProps;

                function addData() {
                    addKctz(curData).then(res => {
                        if (res.code == 0) {
                            message(`数据新增成功`, {
                                type: "success"
                            });
                            done(); // 关闭弹框
                            onSearchKctz(); // 刷新表格数据
                        } else {
                            message(`数据新增失败`, {
                                type: "error"
                            });
                        }
                    });
                }

                function handleUpdate(curData) {
                    updateKctz(curData).then(res => {
                        if (res.code == 0) {
                            message(`数据修改成功`, {
                                type: "success"
                            });
                            done(); // 关闭弹框
                            onSearchKctz(); // 刷新表格数据
                        } else {
                            message(`数据修改失败`, {
                                type: "error"
                            });
                        }
                    });
                }

                FormRef.validate(valid => {
                    debugger
                    if (valid) {
                        console.log("curData", curData);
                        // 表单规则校验通过
                        if (title === "新增") {
                            // 实际开发先调用新增接口，再进行下面操作
                            addData();
                        } else {
                            // 实际开发先调用编辑接口，再进行下面操作
                            handleUpdate(curData);
                        }
                    }
                });
            }
        });
    }

    return {
        loadingKctz,
        searchFormKctz,
        paginationKctz,
        kctzColumns,
        kctzDataList,
        onSearchKctz,
        resetSearchFormKctz,
        handleDeleteKctz,
        handleSizeChangeKctz,
        handleCurrentChangeKctz,
        handleSelectionChangeKctz,
        openDialogKctz
    };
}
